﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;

namespace Shop.Infrastructure.Extensions
{
    public static class ExceptionExtension
    {
        public static string CODEKEY = "CodeKey";
        public static string PARAMSKEY = "ParamsKey";
        /// <summary>
        /// 添加异常附属信息
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="ex"></param>
        /// <param name="exceptionCode">异常代码</param>
        /// <param name="paramList">上下文参数</param>
        /// <returns></returns>
        public static T AddContext<T>(this T ex, int exceptionCode, IDictionary<string, object> paramsDict = null) where T : Exception
        {
            ex.Data.Add(CODEKEY, exceptionCode);
            if (paramsDict != null)
            {
                ex.Data.Add(PARAMSKEY, paramsDict);
            }
            return ex;
        }
        /// <summary>
        /// 添加异常附属信息
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="ex"></param>
        /// <param name="exceptionCode">异常代码</param>
        /// <param name="paramList">上下文参数</param>
        /// <returns></returns>
        public static T AddContext<T>(this T ex, int exceptionCode, object paramsDict = null) where T : Exception
        {
            return ex.AddContext(exceptionCode, paramsDict.AnonymousObjectToDict());
        }
        /// <summary>
        /// 获取异常错误代码，默认为0。
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="ex"></param>
        /// <returns></returns>
        public static int GetCode<T>(this T ex) where T : Exception
        {
            return ex.Data.Contains(CODEKEY) ? (int)ex.Data[CODEKEY] : 0;
        }
        /// <summary>
        /// 获取异常上下文参数。
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="ex"></param>
        /// <returns></returns>
        public static IDictionary<string, object> GetParams<T>(this T ex) where T : Exception
        {
            return ex.Data.Contains(PARAMSKEY) ? (IDictionary<string, object>)ex.Data[PARAMSKEY] : null;
        }
    }
}
